import os
import re
import sys
import tkinter as tk
from tkinter import filedialog, messagebox, ttk, scrolledtext
from modules.config import get_moddata_path
from modules.mod_classifier import ModClassifier
from modules.server_communicator import *
from modules.file_manager import FileManager
from modules.name_normalizer import NameNormalizer
import webbrowser
import urllib.request

class ModClassifierApp:
    def __init__(self, root):
        self.root = root
        self.root.title("模组工匠")
        self.root.geometry("600x550")
        self.root.minsize(600, 550)
        
        # 设置样式
        self.setup_styles()
        
        # 初始化模块
        self.classifier = ModClassifier()
        self.file_manager = FileManager()
        self.normalizer = NameNormalizer()
        
        # 创建界面元素
        self.create_widgets()
        
        # 初始化路径
        self.base_folder_path = ""
        self.mods_folder_path = ""
        self.server_required_folder = ""
        self.server_optional_folder = ""
        self.server_unsupported_folder = ""
        self.unknown_folder = ""
        
        # 分类控制标志
        self.classification_running = False
        
        # 服务端地址
        self.server_url = "http://47.115.171.66:5000"
        
        # 当前显示的界面
        self.current_view = "classification"
        
        # 设置全局modartisanversion
        self.modartisanversion = "1.2.1"
        
    def setup_styles(self):
        """
        设置界面样式
        """
        # 设置主窗口背景色为白色
        self.root.configure(bg="#FFFFFF")
        
        # 定义颜色常量
        self.primary_color = "#4A90E2"  # 浅蓝色
        self.secondary_color = "#FFFFFF"  # 白色
        self.accent_color = "#357ABD"  # 深一点的蓝色
        self.hover_color = "#5DA0E9"  # 悬停时的颜色
        self.text_color = "#333333"  # 深灰色文字
        self.active_tab_color = "#E0E0E0"  # 激活标签页的颜色
        
    def create_rounded_button(self, parent, text, command, **kwargs):
        """
        创建圆角按钮
        """
        bg = kwargs.pop('bg', self.primary_color)
        fg = kwargs.pop('fg', self.secondary_color)
        width = kwargs.pop('width', None)
        
        # 创建按钮样式
        button_style = {
            'bg': bg,
            'fg': fg,
            'font': ("Arial", 12),
            'relief': 'flat',
            'borderwidth': 1,
            'highlightthickness': 0,
            'activebackground': self.accent_color,
            'activeforeground': self.secondary_color
        }
        
        # 合并传入的其他参数
        button_style.update(kwargs)
        
        # 创建按钮
        button = tk.Button(parent, text=text, command=command, **button_style)
        
        # 保存按钮的默认颜色
        button.default_bg = bg
        button.default_fg = fg
        
        # 如果指定了宽度，则设置宽度
        if width:
            button.config(width=width)
            
        # 绑定鼠标进入和离开事件
        button.bind("<Enter>", lambda event: self.on_button_hover(event, button))
        button.bind("<Leave>", lambda event: self.on_button_leave(event, button))
            
        return button
        
    def on_button_hover(self, event, button):
        """
        鼠标进入按钮时改变背景色
        """
        button.config(bg=self.hover_color)
        
    def on_button_leave(self, event, button):
        """
        鼠标离开按钮时恢复正确的背景色
        """
        # 根据当前视图设置正确的按钮颜色
        if button == self.classification_btn:
            if self.current_view == "classification":
                button.config(bg=self.active_tab_color, fg=self.text_color)
            else:
                button.config(bg=self.primary_color, fg=self.secondary_color)
        elif button == self.about_btn:
            if self.current_view == "about":
                button.config(bg=self.active_tab_color, fg=self.text_color)
            else:
                button.config(bg=self.primary_color, fg=self.secondary_color)
        else:
            # 恢复普通按钮的默认颜色
            button.config(bg=button.default_bg, fg=button.default_fg)
        
    def create_widgets(self):
        # 创建顶部导航栏
        self.create_navigation_bar()
        
        # 创建主内容面板
        self.main_panel = tk.Frame(self.root, bg=self.secondary_color)
        self.main_panel.pack(fill=tk.BOTH, expand=True)
        
        # 创建各个界面
        self.create_classification_view()
        self.create_about_view()
        # 默认显示mod分类界面
        self.show_classification_view()

    def create_navigation_bar(self):
        """
        创建顶部导航栏
        """
        nav_frame = tk.Frame(self.root, bg=self.secondary_color, height=40)
        nav_frame.pack(fill=tk.X, padx=0, pady=0)
        nav_frame.pack_propagate(False)
        
        self.classification_btn = self.create_rounded_button(
            nav_frame, "Mod分类", self.show_classification_view, 
            bg=self.active_tab_color, fg=self.text_color, width=20)
        self.classification_btn.pack(side=tk.LEFT, fill=tk.BOTH, expand=True, padx=(0, 1))
        
        self.about_btn = self.create_rounded_button(
            nav_frame, "关于", self.show_about_view, 
            bg=self.primary_color, fg=self.secondary_color, width=20)
        self.about_btn.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
        
        
    def show_classification_view(self):
        """
        显示Mod分类界面
        """
        self.hide_all_views()
        self.classification_frame.pack(fill=tk.BOTH, expand=True)
        self.current_view = "classification"
        
        # 更新按钮状态
        self.classification_btn.config(bg=self.active_tab_color, fg=self.text_color)
        self.about_btn.config(bg=self.primary_color, fg=self.secondary_color)
        
    def show_about_view(self):
        """
        显示关于界面
        """
        self.hide_all_views()
        self.about_frame.pack(fill=tk.BOTH, expand=True)
        self.current_view = "about"
        
        # 更新按钮状态
        self.classification_btn.config(bg=self.primary_color, fg=self.secondary_color)
        self.about_btn.config(bg=self.active_tab_color, fg=self.text_color)

    def hide_all_views(self):
        """
        隐藏所有界面
        """
        self.classification_frame.pack_forget()
        self.about_frame.pack_forget()
        
        

    def create_classification_view(self):
        """
        创建Mod分类界面
        """
        self.classification_frame = tk.Frame(self.main_panel, bg=self.secondary_color)
        
        # 标题
        title_frame = tk.Frame(self.classification_frame, bg=self.secondary_color)
        title_frame.pack(fill=tk.X, padx=20, pady=(10, 5))
        
        title_label = tk.Label(title_frame, text="Mod分类工具", font=("Arial", 16, "bold"), bg=self.secondary_color, fg=self.text_color)
        title_label.pack(side=tk.LEFT)
        
        # MC游戏版本路径选择框架
        base_frame = tk.Frame(self.classification_frame, bg=self.secondary_color)
        base_frame.pack(fill=tk.X, padx=20, pady=5)
        
        base_label = tk.Label(base_frame, text="MC游戏版本路径(例如C:/Users/suiyi/AppData/Local/pcl/.minecraft/versions/1.20.1-Forge_47.4.0):", 
                             bg=self.secondary_color, fg=self.text_color)
        base_label.pack(anchor=tk.W)
        
        base_path_frame = tk.Frame(base_frame, bg=self.secondary_color)
        base_path_frame.pack(fill=tk.X, pady=5)
        
        self.base_path_var = tk.StringVar()
        self.base_path_var.trace('w', self.on_path_change)  # 添加路径变化监听
        base_path_entry = tk.Entry(base_path_frame, textvariable=self.base_path_var, relief="solid", borderwidth=1)
        base_path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        browse_button = self.create_rounded_button(base_path_frame, "浏览...", self.browse_base_folder, bg=self.primary_color, width=8)
        browse_button.pack(side=tk.RIGHT, padx=(5, 0))
        
        # ModData.txt框架
        moddata_frame = tk.Frame(self.classification_frame, bg=self.secondary_color)
        moddata_frame.pack(fill=tk.X, padx=20, pady=5)
        
        moddata_label = tk.Label(moddata_frame, text="ModData.txt文件(首次使用需下载该文件):", 
                                bg=self.secondary_color, fg=self.text_color)
        moddata_label.pack(anchor=tk.W)
        
        moddata_path_frame = tk.Frame(moddata_frame, bg=self.secondary_color)
        moddata_path_frame.pack(fill=tk.X, pady=5)
        
        self.moddata_path_var = tk.StringVar(value=get_moddata_path())
        moddata_path_entry = tk.Entry(moddata_path_frame, textvariable=self.moddata_path_var, state="readonly", relief="solid", borderwidth=1)
        moddata_path_entry.pack(side=tk.LEFT, fill=tk.X, expand=True)
        
        download_button = self.create_rounded_button(moddata_path_frame, "下载", self.download_moddata, bg=self.primary_color, width=8)
        download_button.pack(side=tk.RIGHT, padx=(5, 0))
        
        # 日志显示区域
        log_frame = tk.Frame(self.classification_frame, bg=self.secondary_color)
        log_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=5)
        
        log_label = tk.Label(log_frame, text="运行日志:", bg=self.secondary_color, fg=self.text_color)
        log_label.pack(anchor=tk.W)
        
        self.log_text = scrolledtext.ScrolledText(log_frame, height=10, relief="solid", borderwidth=1)
        self.log_text.pack(fill=tk.BOTH, expand=True, pady=5)
        
        # 进度条
        self.progress_frame = tk.Frame(self.classification_frame, bg=self.secondary_color)
        self.progress_frame.pack(fill=tk.X, padx=20, pady=5)
        
        self.progress_label = tk.Label(self.progress_frame, text="进度:", bg=self.secondary_color, fg=self.text_color)
        self.progress_label.pack(anchor=tk.W)
        
        self.progress_var = tk.DoubleVar()
        self.progress_bar = ttk.Progressbar(self.progress_frame, variable=self.progress_var, maximum=100)
        self.progress_bar.pack(fill=tk.X, pady=5)
        
        self.progress_text = tk.Label(self.progress_frame, text="等待开始...", bg=self.secondary_color, fg=self.text_color)
        self.progress_text.pack(anchor=tk.W)
        
        # 确保底部控件可见的占位框架
        bottom_spacer = tk.Frame(self.classification_frame, bg=self.secondary_color, height=10)
        bottom_spacer.pack()
        
        # 按钮框架
        button_frame = tk.Frame(self.classification_frame, bg=self.secondary_color)
        button_frame.pack(pady=10, fill=tk.X)
        
        # 创建一个内部框架用于居中按钮
        button_inner_frame = tk.Frame(button_frame, bg=self.secondary_color)
        button_inner_frame.pack(expand=True)
        
        # 开始分类按钮
        self.start_button = self.create_rounded_button(button_inner_frame, "开始分类", self.start_classification, 
                                                      bg=self.primary_color, fg=self.secondary_color, 
                                                      font=("Arial", 12), width=10, state=tk.DISABLED)
        self.start_button.pack(side=tk.LEFT, padx=(0, 10))
        
        # 停止按钮
        self.stop_button = self.create_rounded_button(button_inner_frame, "停止", self.stop_classification, 
                                                     bg=self.primary_color, fg=self.secondary_color, 
                                                     font=("Arial", 12), width=10, state=tk.DISABLED)
        self.stop_button.pack(side=tk.LEFT)
        
    def create_about_view(self):
        """
        创建关于界面
        """
        self.about_frame = tk.Frame(self.main_panel, bg=self.secondary_color)
        
        # 标题
        title_frame = tk.Frame(self.about_frame, bg=self.secondary_color)
        title_frame.pack(fill=tk.X, padx=20, pady=(10, 5))
        
        title_label = tk.Label(title_frame, text="关于", font=("Arial", 16, "bold"), bg=self.secondary_color, fg=self.text_color)
        title_label.pack(side=tk.LEFT)
        
        # 内容区域
        content_frame = tk.Frame(self.about_frame, bg=self.secondary_color)
        content_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=20)
        
        # 创建设置项
        frame = tk.Frame(content_frame, bg=self.secondary_color)
        frame.pack(expand=True)
        
        # 赞助按钮
        sponsor_btn = self.create_rounded_button(frame, "赞助", self.sponsor, bg=self.primary_color, width=20)
        sponsor_btn.pack(pady=10)
        
        # 联系作者按钮
        contact_btn = self.create_rounded_button(frame, "联系作者", self.contact_author, bg=self.primary_color, width=20)
        contact_btn.pack(pady=10)
        
        # 检查版本按钮
        check_version_btn = self.create_rounded_button(frame, "检查版本", self.check_version_with_pan_links, bg=self.primary_color, width=20)
        check_version_btn.pack(pady=10)
        
    def on_path_change(self, *args):
        """
        当路径文本发生变化时调用
        """
        folder_selected = self.base_path_var.get()
        if folder_selected:
            self.base_folder_path = folder_selected
            self.mods_folder_path = os.path.join(folder_selected, "mods")
            self.server_required_folder = os.path.join(folder_selected, "服务端需装")
            self.server_optional_folder = os.path.join(folder_selected, "服务端可选")
            self.server_unsupported_folder = os.path.join(folder_selected, "服务端无效")
            self.unknown_folder = os.path.join(folder_selected, "无法识别")
            
            # 检查mods文件夹是否存在
            if os.path.exists(self.mods_folder_path):
                self.start_button.config(state=tk.NORMAL)
            else:
                self.start_button.config(state=tk.DISABLED)
        else:
            self.start_button.config(state=tk.DISABLED)
    
    
    def browse_base_folder(self):
        folder_selected = filedialog.askdirectory(title="请选择MC游戏版本路径")
        if folder_selected:
            self.base_path_var.set(folder_selected)
            # on_path_change会自动处理后续逻辑
    
    def download_moddata(self):
        # 在新线程中运行下载，避免界面冻结
        import threading
        thread = threading.Thread(target=self._download_moddata_thread)
        thread.daemon = True
        thread.start()
    
    def _download_moddata_thread(self):
        moddata_url = "https://raw.githubusercontent.com/Meloong-Git/PCL/refs/heads/main/Plain%20Craft%20Launcher%202/Resources/ModData.txt"
        try:
            self.log_message("正在下载 ModData.txt...")
            response = urllib.request.urlopen(moddata_url, timeout=30)  # 设置30秒超时
            # 确保MODDATA_FILE_PATH指向exe所在目录而不是临时目录
            moddata_path = os.path.join(os.path.dirname(sys.executable), "ModData.txt") if getattr(sys, 'frozen', False) else get_moddata_path()
            
            # 检查响应是否有效
            if response.getcode() == 200:
                with open(moddata_path, "wb") as f:
                    f.write(response.read())
                
                # 检查文件是否成功下载
                if os.path.exists(moddata_path) and os.path.getsize(moddata_path) > 0:
                    self.root.after(0, lambda: self.moddata_path_var.set(moddata_path))
                    self.log_message(f"ModData.txt 下载完成: {moddata_path}")
                    self.root.after(0, lambda: messagebox.showinfo("成功", "ModData.txt 下载完成!"))
                else:
                    # 如果文件大小为0，删除它
                    if os.path.exists(moddata_path):
                        os.remove(moddata_path)
                    self.log_message("下载失败: 下载的文件为空")
                    self.root.after(0, lambda: messagebox.showerror("错误", "下载 ModData.txt 失败:\n下载的文件为空"))
            else:
                self.log_message(f"下载失败: HTTP {response.getcode()}")
                self.root.after(0, lambda: messagebox.showerror("错误", f"下载 ModData.txt 失败:\nHTTP {response.getcode()}"))
        except Exception as e:
            self.log_message(f"下载失败: {str(e)}")
            self.root.after(0, lambda: messagebox.showerror("错误", f"下载 ModData.txt 失败:\n{str(e)}"))
    
    def log_message(self, message):
        self.log_text.insert(tk.END, message + "\n")
        self.log_text.see(tk.END)
        self.root.update()
    
    def start_classification(self):
        # 在新线程中运行分类，避免界面冻结
        import threading
        self.classification_running = True
        self.start_button.config(state=tk.DISABLED)
        self.stop_button.config(state=tk.NORMAL)
        thread = threading.Thread(target=self.run_classification)
        thread.daemon = True
        thread.start()
    
    def stop_classification(self):
        self.classification_running = False
        self.log_message("正在停止分类...")
        self.start_button.config(state=tk.NORMAL)
        self.stop_button.config(state=tk.DISABLED)
    
    def run_classification(self):
        try:
            self.log_message("开始分类...")
            
            # 检查配置
            if not self.base_folder_path:
                self.log_message("请先选择基础目录路径！")
                return
            
            if not os.path.exists(self.base_folder_path):
                self.log_message(f"基础文件夹路径不存在: {self.base_folder_path}")
                return
                
            if not os.path.exists(self.mods_folder_path):
                self.log_message(f"mods文件夹路径不存在: {self.mods_folder_path}")
                return
                
            # 使用正确的ModData.txt路径
            moddata_path = get_moddata_path()
            if not os.path.exists(moddata_path):
                self.log_message(f"ModData.txt文件路径不存在: {moddata_path}")
                self.log_message("请先下载ModData.txt文件")
                return
            
            # 从服务端下载最新的mod环境信息（每天最多下载一次，除非本地没有该文件）
            self.log_message("正在从服务端下载最新的mod环境信息...")
            download_mod_environments_from_server(self.server_url)
            temp_mod_environments_json_inti()
            # 清空分类文件夹
            folders = [
                self.server_required_folder,
                self.server_optional_folder,
                self.server_unsupported_folder,
                self.unknown_folder
            ]
            self.file_manager.clear_classification_folders(folders)
            
            # 处理mods文件夹
            self.process_mods_folder(self.mods_folder_path)
            
            if self.classification_running:
                # 在向服务端发送运行环境信息时加上modartisanversion键值对
                update_temp_mod_environments_json("modartisanversion", self.modartisanversion)
                sync_result = sync_mod_environments_with_server(self.server_url)
                if sync_result == 'update_required':
                    self.log_message("检测到新版本，请更新客户端！")
                    # 在UI线程中显示更新提示
                    self.root.after(100, self.prompt_for_update)
                else:
                    self.log_message("分类完成！")
        except Exception as e:
            self.log_message(f"分类过程中出现错误: {str(e)}")
        finally:
            self.classification_running = False
            self.start_button.config(state=tk.NORMAL)
            self.stop_button.config(state=tk.DISABLED)
    
    def process_mods_folder(self, folder_path):
        """
        遍历mods文件夹中的每个mod，获取其服务端支持环境并分类
        """
        jar_files = self.file_manager.process_mods_folder(folder_path)
        
        if not jar_files:
            return
        
        total_files = len(jar_files)
        self.log_message(f"找到 {total_files} 个mod文件")
        self.log_message("-" * 80)
        
        # 处理每个mod文件
        for index, jar_file in enumerate(jar_files):
            # 检查是否需要停止
            if not self.classification_running:
                self.log_message("分类已停止")
                return
            
            # 更新进度条
            progress = (index + 1) / total_files * 100
            self.progress_var.set(progress)
            self.progress_text.config(text=f"进度: {index + 1}/{total_files} ({progress:.1f}%)")
            
            filename = os.path.basename(jar_file)
            self.log_message(f"处理: {filename}")
            
            # 使用新的分类方法，优先从JSON文件获取环境信息
            classification = self.classifier.classify_mod(jar_file)
            
            # 检查是否需要停止
            if not self.classification_running:
                self.log_message("分类已停止")
                return
            
            # 移动文件到对应文件夹
            if self.file_manager.move_mod_to_folder(
                jar_file, classification,
                self.server_required_folder,
                self.server_optional_folder,
                self.server_unsupported_folder,
                self.unknown_folder):
                # 显示分类结果
                classification_names = {
                    'required': '服务端需装',
                    'optional': '服务端可选',
                    'unsupported': '服务端无效',
                    'unknown': '无法识别'
                }
                
                self.log_message(f"  分类结果: {classification_names.get(classification, '未知')}")
            else:
                self.log_message(f"  文件复制失败")
            
            self.log_message("-" * 80)
        
        # 分类完成，设置进度为100%
        self.progress_var.set(100)
        self.progress_text.config(text=f"进度: {total_files}/{total_files} (100.0%)")
    
    def sponsor(self):
        """
        赞助功能
        """
        try:
            webbrowser.open("https://afdian.com/a/taisuiyileba")
        except Exception as e:
            messagebox.showerror("错误", f"无法打开赞助页面：{str(e)}")
    
    def contact_author(self):
        """
        联系作者功能
        """
        messagebox.showinfo("联系作者", "您可以通过以下方式联系作者：\n\n邮箱：3416219326@qq.com\nQQ群：1049492704\nGitHub：github.com/taisuiyileba/mod_classifier")
    

    def prompt_for_update(self):
        """
        提示用户更新客户端
        """
        try:
            response = requests.get("https://raw.githubusercontent.com/taisuiyileba/mod_classifier/refs/heads/master/latest_version.json")
            content_str = response.content.decode('utf-8')
            fixed_json = re.sub(r'([{,]\s*)([a-zA-Z_][a-zA-Z0-9_]*)(\s*:)', r'\1"\2"\3', content_str)
            data = json.loads(fixed_json)
            latest_version = data.get('latest_version')
            
            # 创建更新提示对话框
            update_window = tk.Toplevel(self.root)
            update_window.title("需要更新")
            update_window.geometry("400x300")
            update_window.resizable(False, False)
            update_window.configure(bg=self.secondary_color)
            
            # 居中显示
            update_window.transient(self.root)
            update_window.grab_set()
            
            x = self.root.winfo_x() + (self.root.winfo_width() // 2) - (400 // 2)
            y = self.root.winfo_y() + (self.root.winfo_height() // 2) - (300 // 2)
            update_window.geometry(f"+{x}+{y}")
            
            # 标题
            title_label = tk.Label(update_window, text="需要更新", font=("Arial", 16, "bold"), 
                                  bg=self.secondary_color, fg=self.text_color)
            title_label.pack(pady=10)
            
            # 版本信息
            version_info = tk.Label(update_window, 
                                   text=f"当前版本已停用\n请更新到最新版本：v{latest_version}",
                                   bg=self.secondary_color, fg=self.text_color, justify=tk.LEFT)
            version_info.pack(pady=5)
            
            # 提示信息
            prompt_label = tk.Label(update_window, 
                                   text="请选择下载方式：",
                                   bg=self.secondary_color, fg=self.text_color, justify=tk.LEFT)
            prompt_label.pack(pady=(10, 5))
            
            # 网盘链接按钮框架
            links_frame = tk.Frame(update_window, bg=self.secondary_color)
            links_frame.pack(pady=10)
            
            # 检查是否有网盘链接
            download_links = data.get('download_links', {})
            
            # 夸克网盘按钮
            quark_link = download_links.get('quark')
            if quark_link:
                quark_btn = self.create_rounded_button(links_frame, "夸克网盘下载", 
                                                      lambda: webbrowser.open(quark_link),
                                                      bg=self.primary_color, width=20)
                quark_btn.pack(pady=5)
            
            # 百度网盘按钮
            baidu_link = download_links.get('baidu')
            if baidu_link:
                baidu_btn = self.create_rounded_button(links_frame, "百度网盘下载", 
                                                      lambda: webbrowser.open(baidu_link),
                                                      bg=self.primary_color, width=20)
                baidu_btn.pack(pady=5)
            
            # 123网盘按钮
            netdisk123_link = download_links.get('123')
            if netdisk123_link:
                netdisk123_btn = self.create_rounded_button(links_frame, "123网盘下载", 
                                                           lambda: webbrowser.open(netdisk123_link),
                                                           bg=self.primary_color, width=20)
                netdisk123_btn.pack(pady=5)
                
            # 提示标签
            tip_label = tk.Label(update_window, 
                                text="提示：部分网盘可能需要提取码，请查看发布说明",
                                bg=self.secondary_color, fg="gray", font=("Arial", 9))
            tip_label.pack(side=tk.BOTTOM, pady=10)
            
        except Exception as e:
            messagebox.showerror("错误", f"获取更新信息时出错：{str(e)}")

    def check_version_with_pan_links(self):
        """
        检查版本功能，包含网盘链接
        """
        try:
            # 获取当前版本号
            response = requests.get("https://raw.githubusercontent.com/taisuiyileba/mod_classifier/refs/heads/master/latest_version.json")
            content_str = response.content.decode('utf-8')
            fixed_json = re.sub(r'([{,]\s*)([a-zA-Z_][a-zA-Z0-9_]*)(\s*:)', r'\1"\2"\3', content_str)
            data = json.loads(fixed_json)
            latest_version = data.get('latest_version')
            
            if self.modartisanversion == latest_version:
                messagebox.showinfo("版本检查", f"当前已是最新版本：v{self.modartisanversion}")
            else:
                # 创建新版本对话框
                version_window = tk.Toplevel(self.root)
                version_window.title("发现新版本")
                version_window.geometry("400x300")
                version_window.resizable(False, False)
                version_window.configure(bg=self.secondary_color)
                
                # 居中显示
                version_window.transient(self.root)
                version_window.grab_set()
                
                x = self.root.winfo_x() + (self.root.winfo_width() // 2) - (400 // 2)
                y = self.root.winfo_y() + (self.root.winfo_height() // 2) - (300 // 2)
                version_window.geometry(f"+{x}+{y}")
                
                # 标题
                title_label = tk.Label(version_window, text="发现新版本", font=("Arial", 16, "bold"), 
                                      bg=self.secondary_color, fg=self.text_color)
                title_label.pack(pady=10)
                
                # 版本信息
                version_info = tk.Label(version_window, 
                                       text=f"当前版本：v{self.modartisanversion}\n最新版本：v{latest_version}",
                                       bg=self.secondary_color, fg=self.text_color, justify=tk.LEFT)
                version_info.pack(pady=5)
                
                # 提示信息
                prompt_label = tk.Label(version_window, 
                                       text="请选择下载方式：",
                                       bg=self.secondary_color, fg=self.text_color, justify=tk.LEFT)
                prompt_label.pack(pady=(10, 5))
                
                # 网盘链接按钮框架
                links_frame = tk.Frame(version_window, bg=self.secondary_color)
                links_frame.pack(pady=10)
                
                # 检查是否有网盘链接
                download_links = data.get('download_links', {})
                has_links = False
                
                # 夸克网盘按钮
                quark_link = download_links.get('quark')
                if quark_link:
                    quark_btn = self.create_rounded_button(links_frame, "夸克网盘下载", 
                                                          lambda: webbrowser.open(quark_link),
                                                          bg=self.primary_color, width=20)
                    quark_btn.pack(pady=5)
                    has_links = True
                
                # 百度网盘按钮
                baidu_link = download_links.get('baidu')
                if baidu_link:
                    baidu_btn = self.create_rounded_button(links_frame, "百度网盘下载", 
                                                          lambda: webbrowser.open(baidu_link),
                                                          bg=self.primary_color, width=20)
                    baidu_btn.pack(pady=5)
                    has_links = True
                
                # 123网盘按钮
                netdisk123_link = download_links.get('123')
                if netdisk123_link:
                    netdisk123_btn = self.create_rounded_button(links_frame, "123网盘下载", 
                                                               lambda: webbrowser.open(netdisk123_link),
                                                               bg=self.primary_color, width=20)
                    netdisk123_btn.pack(pady=5)
                    has_links = True
                # 提示标签
                tip_label = tk.Label(version_window, 
                                    text="提示：部分网盘可能需要提取码，请查看发布说明",
                                    bg=self.secondary_color, fg="gray", font=("Arial", 9))
                tip_label.pack(side=tk.BOTTOM, pady=10)
                
        except Exception as e:
            messagebox.showerror("错误", f"检查版本时出错：{str(e)}")

def main():
    """
    主函数
    """
    root = tk.Tk()
    app = ModClassifierApp(root)
    root.mainloop()

if __name__ == "__main__":
    main()